/**
 * Copyright &copy; 2012-2017 <a href="https://vivo.com/">vivo</a> All rights reserved.
 */
package com.vivo.system.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.vivo.system.entity.ViSysRoleMap;
import com.vivo.system.service.ViSysRoleMapService;

import java.util.ArrayList;
import java.util.List;

/**
 * IDC同步岗位映射Controller
 * @author jyangye
 * @version 2018-04-16
 */
@Controller
@RequestMapping(value = "${adminPath}/system/viSysRoleMap")
public class ViSysRoleMapController extends BaseController {

	@Autowired
	private ViSysRoleMapService viSysRoleMapService;
	
	@ModelAttribute
	public ViSysRoleMap get(@RequestParam(required=false) String id) {
		ViSysRoleMap entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = viSysRoleMapService.get(id);
		}
		if (entity == null){
			entity = new ViSysRoleMap();
		}
		return entity;
	}
	
	@RequiresPermissions("system:viSysRoleMap:view")
	@RequestMapping(value = {"list", ""})
	public String list(ViSysRoleMap viSysRoleMap, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ViSysRoleMap> page = viSysRoleMapService.findPage(new Page<ViSysRoleMap>(request, response), viSysRoleMap); 
		model.addAttribute("page", page);
		return "vivo/system/viSysRoleMapList";
	}

	@RequiresPermissions("system:viSysRoleMap:view")
	@RequestMapping(value = "form")
	public String form(ViSysRoleMap viSysRoleMap, Model model) {
		model.addAttribute("viSysRoleMap", viSysRoleMap);
		return "vivo/system/viSysRoleMapForm";
	}

	@RequiresPermissions("system:viSysRoleMap:edit")
	@RequestMapping(value = "save")
	public String save(ViSysRoleMap viSysRoleMap, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, viSysRoleMap)){
			return form(viSysRoleMap, model);
		}
		viSysRoleMapService.save(viSysRoleMap);
		addMessage(redirectAttributes, "保存IDC同步岗位映射成功");
		return "redirect:"+Global.getAdminPath()+"/system/viSysRoleMap/?repage";
	}
	
	@RequiresPermissions("system:viSysRoleMap:edit")
	@RequestMapping(value = "delete")
	public String delete(ViSysRoleMap viSysRoleMap, RedirectAttributes redirectAttributes) {
		viSysRoleMapService.delete(viSysRoleMap);
		addMessage(redirectAttributes, "删除IDC同步岗位映射成功");
		return "redirect:"+Global.getAdminPath()+"/system/viSysRoleMap/?repage";
	}


	@RequiresPermissions("system:viSysRoleMap:edit")
	@RequestMapping(value = "active")
	public String active(ViSysRoleMap viSysRoleMap, RedirectAttributes redirectAttributes) {
		viSysRoleMap.setIsActive("0");
		addMessage(redirectAttributes, "启用IDC同步岗位映射成功");
		return "redirect:"+Global.getAdminPath()+"/system/viSysRoleMap/?repage";
	}

	/**
	 * 批量删除IDC同步岗位映射
	 */
	@RequiresPermissions("system:viSysRoleMap:edit")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			viSysRoleMapService.delete(viSysRoleMapService.get(id));
		}
		addMessage(redirectAttributes, "删除IDC同步岗位映射成功");
		return "redirect:"+Global.getAdminPath()+"/system/viSysRoleMap/?repage";
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("system:viSysRoleMap:edit")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(ViSysRoleMap viSysRoleMap, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "IDC同步岗位映射"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<ViSysRoleMap> page = viSysRoleMapService.findPage(new Page<ViSysRoleMap>(request, response, -1), viSysRoleMap);
    		new ExportExcel("IDC同步岗位映射", ViSysRoleMap.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出IDC同步岗位映射记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/system/viSysRoleMap/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("system:viSysRoleMap:edit")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes, HttpServletRequest request, HttpServletResponse response) {
	    List<ViSysRoleMap> errList = new ArrayList<ViSysRoleMap>();

		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<ViSysRoleMap> list = ei.getDataList(ViSysRoleMap.class);
			for (ViSysRoleMap viSysRoleMap : list){
			    if (StringUtils.isBlank(viSysRoleMap.getViPostName())) {
			        viSysRoleMap.setErrMsg("IDC岗位不能为空！");
                    errList.add(viSysRoleMap);
			        failureNum++;
			        continue;
                }

                if(StringUtils.isBlank(viSysRoleMap.getSysRoleName())) {
                    viSysRoleMap.setErrMsg("优信通角色名称不能为空！");
                    errList.add(viSysRoleMap);
                    failureNum++;
                    continue;
                }

                if(StringUtils.isBlank(viSysRoleMap.getSysRoleId())) {
                    viSysRoleMap.setErrMsg("优信通角色ID不能为空！");
                    errList.add(viSysRoleMap);
                    failureNum++;
                    continue;
                }

                if(StringUtils.isBlank(viSysRoleMap.getSysPostName())) {
                    viSysRoleMap.setErrMsg("优信通岗位不能为空！");
                    errList.add(viSysRoleMap);
                    failureNum++;
                    continue;
                }

                if(StringUtils.isBlank(viSysRoleMap.getZone())) {
                    viSysRoleMap.setErrMsg("岗位归属区域不能为空！");
                    errList.add(viSysRoleMap);
                    failureNum++;
                    continue;
                }

				try{
					viSysRoleMapService.save(viSysRoleMap);
					successNum++;
				}catch(ConstraintViolationException ex) {
			        viSysRoleMap.setErrMsg(ex.getMessage());
			        errList.add(viSysRoleMap);
					failureNum++;
				}catch (Exception ex) {
                    viSysRoleMap.setErrMsg(ex.getMessage());
                    errList.add(viSysRoleMap);
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条IDC同步岗位映射记录。");
			}

			if (errList.size() > 0) {
                new ExportExcel("IDC同步岗位映射导入错误信息", ViSysRoleMap.class).setDataList(errList).write(response, "IDC同步岗位导入错误列表").dispose();
            }

			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条IDC同步岗位映射记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入IDC同步岗位映射失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/system/viSysRoleMap/?repage";
    }

	/**
	 * 下载导入{functionNameSimple}数据模板
	 */
	@RequiresPermissions("system:viSysRoleMap:edit")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "IDC同步岗位映射数据导入模板.xlsx";
    		List<ViSysRoleMap> list = Lists.newArrayList();
    		new ExportExcel("IDC同步岗位映射数据", ViSysRoleMap.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/system/viSysRoleMap/?repage";
    }

}